package com.chendx.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chendx.behavior.mapper.ApUnlikesBehaviorMapper;
import com.chendx.behavior.service.ApUnlikesBehaviorService;
import com.chendx.model.behavior.dtos.UnLikesBehaviorDto;
import com.chendx.model.behavior.pojos.ApBehaviorEntry;
import com.chendx.model.behavior.pojos.ApUnlikesBehavior;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.user.pojos.ApUser;
import com.chendx.utils.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by chendx on 2022/3/8.
 */
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper,ApUnlikesBehavior> implements ApUnlikesBehaviorService{

    @Autowired
    private ApBehaviorEntryServiceImpl apBehaviorEntryService;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        if (dto == null || dto.getType() < 0 || dto.getType() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtils.get();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), null);
        if (apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                                                            .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId())
                                                            .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));
        if (apUnlikesBehavior == null && dto.getType() == 0){
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            save(apUnlikesBehavior);
        }else{
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            updateById(apUnlikesBehavior);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
